<template>
  <div>
    <el-row>
      <el-button type="danger" @click="batchDelCategory">批量删除</el-button>
    </el-row>

    <!-- expand-on-click-node属性，默认为true，是否点击节点展开或者收缩节点列表
         show-checkbox属性，不写该属性默认为false，是否展示节点的多选框，并且自带全选全不选
         node-key属性，代表该节点的唯一标识
         default-expanded-keys属性，需要绑定一个数组，默认展开的树形节点（传入其id即可） -->
    <el-tree
      :data="menuDataSource"
      :props="defaultProps"
      show-checkbox
      :expand-on-click-node="false"
      node-key="catId"
      ref="menuTree"
      :default-expanded-keys="defaultShowTreeNode"
      @node-click="getMoreLvMenu"
    >
      <!-- 添加树形结构的后部按钮 -->
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <!-- 分类等级为一级或者二级的时候才能追加子分类 -->
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <!-- 修改分类数据 -->
          <el-button type="text" size="mini" @click="Edit(data)">
            Edit
          </el-button>
          <!-- 只有没有子节点的时候才能删除当前节点 -->
          <el-button
            v-if="node.childNodes.length === 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <!-- 添加弹出的对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="category">
        <el-form-item label="分类图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="category">
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "",
      dialogType: "", //“update”或“add”
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: "",
        productUnit: "",
      },
      dialogFormVisible: false,
      menuDataSource: [],
      defaultShowTreeNode: [],
      defaultProps: {
        children: "childrenCategory",
        label: "name",
      },
    };
  },
  //生命周期-Vue实例创建完成（可以用this访问当前实例了）
  created() {
    this.getMoreLvMenu();
  },
  methods: {
    // 获取多级分类数据列表
    getMoreLvMenu() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
        //注意then里的解构写法'（{data}）'
      }).then(({ data }) => {
        //将查询的数据绑定到vue多级分类组件上
        this.menuDataSource = data.data;
      });
    },
    batchDelCategory(){
      let catIds = [];
      let catNames = [];
      //获取所有选中的树形节点
      //注意：menuTree是属性节点里设置的refs属性，根据此来拿到树形节点的绑定的node-key
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      for(let i = 0;i < checkedNodes.length;i++){
        catIds.push(checkedNodes[i].catId);
        catNames.push(checkedNodes[i].name);
      }
      this.$confirm(`是否批量删除该【${catNames}】等分类?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //确认批量删除，向后端发送批量删除请求
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            //将删除的id传入
            data: this.$http.adornData(catIds, false),
          })
            .then(({ data }) => {
              //删除成功后弹出提示框
              this.$message({
                message: "分类菜单批量删除成功",
                type: "success",
              });
              //刪除后刷新整个菜单
              this.getMoreLvMenu();
            })
            .catch(({ data }) => {
              //删除失败后弹出提示框
              this.$message.error(`批量删除失败：【${data.message}】`);
            });
        })
        .catch(() => {
          //取消删除操作
          this.$message({
            type: "info",
            message: "已取消批量删除",
          });
        });
    },
    //绑定对话框“提交”按钮，根据对话框类型发送不同请求
    submitData() {
      if (this.dialogType === "update") {
        this.editCategory();
      }
      if (this.dialogType === "add") {
        this.addCategory();
      }
    },
    Edit(data) {
      console.log("将要修改的数据：", data);
      //弹出对话框
      this.dialogType = "update";
      this.title = "修改分类";
      this.dialogFormVisible = true;
      //请求查询最新数据用于回显，避免数据非最新数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        console.log("将回显的数据：", data);
        //对话框  回显查询的最新数据
        this.category.name = data.category.name;
        this.category.catId = data.category.catId;
        this.category.icon = data.category.icon;
        this.category.productUnit = data.category.productUnit;
        //回显分类父节点id，用于修改成功后展开列表
        this.category.parentCid = data.category.parentCid;
        //回显默认层级、分类id、排序层级等，用于修改后避免被默认值覆盖
        this.category.catLevel = data.category.catLevel;
        this.category.showStatus = data.category.showStatus;
        this.category.sort = data.category.sort;
      });
    },
    editCategory() {
      //如果前端属性命名和后端实体属性名一致，可以如下缩写。否则是{实体属性名：前端属性名,...}
      //获取修改的属性值
      var { catId, name, icon, productUnit } = this.category;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      }).then(({ data }) => {
        //修改成功
        this.$message({
          message: "分类修改成功",
          type: "success",
        });
        //添加后关掉对话框
        this.dialogFormVisible = false;
        //添加后刷新整个菜单
        this.getMoreLvMenu();
        //将添加的该节点的父节点的id赋值给树形结构默认展示的节点
        this.defaultShowTreeNode = [this.category.parentCid];
      });
    },
    //树形结构的节点新增
    append(data) {
      console.log("append", data);
      //当点击节点的append时候，打开对话框
      this.dialogType = "add";
      this.title = "新增分类";
      this.dialogFormVisible = true;
      //新增分类的父id为点击新增node分类的节点的catId
      this.category.parentCid = data.catId;
      //新增分类的
      this.category.catLevel = data.catLevel * 1 + 1;
      //将非对话框输入的关键信息进行绑定默认值，避免修改后的数据模型为变动
      this.category.name = "";
      this.category.catId = null;
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.showStatus = 1;
      this.category.sort = 0;
    },
    addCategory() {
      console.log("即将添加的分类信息：", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        //将添加的分类信息传入
        data: this.$http.adornData(this.category, false),
      })
        .then(({ data }) => {
          //添加成功后弹出提示框
          this.$message({
            message: "分类添加成功",
            type: "success",
          });
          //添加后关掉对话框
          this.dialogFormVisible = false;
          //添加后刷新整个菜单
          this.getMoreLvMenu();
          //将添加的该节点的父节点的id赋值给树形结构默认展示的节点
          this.defaultShowTreeNode = [this.category.parentCid];
        })
        .catch(({ data }) => {
          //添加失败后弹出提示框
          this.$message.error(`添加失败：【${data.message}】`);
        });
    },
    //树形结构的节点移除
    remove(node, data) {
      //获取当前节点的id
      var ids = [data.catId];
      //点击删除弹出确认框
      this.$confirm(`是否删除该【${data.name}】分类菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //确认删除，向后端发送批量删除请求
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            //将删除的id传入
            data: this.$http.adornData(ids, false),
          })
            .then(({ data }) => {
              //删除成功后弹出提示框
              this.$message({
                message: "分类菜单删除成功",
                type: "success",
              });
              //刪除后刷新整个菜单
              this.getMoreLvMenu();
              //将删除的该节点的父节点的id赋值给树形结构默认展示的节点
              this.defaultShowTreeNode = [node.parent.data.catId];
            })
            .catch(({ data }) => {
              //删除失败后弹出提示框
              this.$message.error(`删除失败：【${data.message}】`);
            });
        })
        .catch(() => {
          //取消删除操作
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style scoped>
</style>